1 /*
2 Copyright: Marcelo S. N. Mancini (Hipreme|MrcSnm), 2018 - 2021
3 License:   [https://creativecommons.org/licenses/by/4.0/|CC BY-4.0 License].
4 Authors: Marcelo S. N. Mancini
5 
6 	Copyright Marcelo S. N. Mancini 2018 - 2021.
7 Distributed under the CC BY-4.0 License.
8    (See accompanying file LICENSE.txt or copy at
9 	https://creativecommons.org/licenses/by/4.0/
10 */
11 
12 module hip.graphics.g2d.tilemap;
13 public import hip.graphics.g2d.spritebatch;
14 public import hip.assets.texture;
15 public import hip.api.data.tilemap;
16 
17 import hip.util.reflection;
18 enum hasTSXSupport = Version.HipTSX && hasModule!"arsd.dom";
19 
20 
21 void render(HipTileLayer layer, IHipTilemap map, HipSpriteBatch batch, bool shouldRenderBatch = false)
22 {
23     uint w = layer.columns, h = layer.rows;
24 
25     uint th = cast(uint)(map.tileHeight*map.scaleY),
26          tw = cast(uint)(map.tileWidth*map.scaleX);
27 
28     ushort lastId;
29     IHipTextureRegion lastTexture;
30 
31 
32     for(int i = 0, y = layer.y; i < h; i++, y+= th)
33         for(int j =0, x = layer.x; j < w; j++, x+= tw)
34         {
35             ushort targetTile = layer.tiles[i*w+j];
36             if(targetTile == 0)
37                 continue;
38             if(lastId != targetTile)
39             {
40                 /**
41                 * Probably worth caching as it is: 
42                 * - one pointer dereference (map->)
43                 * - one function call (getTextureRegionForID)
44                 * - one function call (getTilesetForID)
45                 * - one pointer derefenrece (tileset->)
46                 * - one function call (getTextureRegion)
47                 */
48                 lastId = targetTile;
49                 lastTexture = map.getTextureRegionForID(targetTile);
50             }
51             batch.draw(lastTexture, map.x + x,  map.y + y, 0, map.color, map.scaleX, map.scaleY, map.rotation);
52         }
53 
54     if(shouldRenderBatch)
55         batch.draw();
56 }
57 
58 void render(IHipTilemap map, HipSpriteBatch batch, bool shouldRenderBatch)
59 {
60     foreach(l; map.layers)
61         l.render(map, batch, false);
62     if(shouldRenderBatch)
63         batch.draw();
64 }